package cn.walmt.service;

import cn.walmt.entity.User;
import cn.walmt.exception.HttpException;
import cn.walmt.mapper.UserMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jdk.nashorn.internal.ir.IfNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import util.GsonUtil;
import util.HttpsUtil;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * 用户功能方面的处理
 * Created by walmt on 2018/1/17.
 */
@Service
@Transactional
public class UserService {

    @Value("${appid}")
    private String appid;

    @Autowired
    private UserMapper userMapper;

    public String selectUserById(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        return GsonUtil.getSuccessJson(user);
    }

    public User selectUserByUserId(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 登陆
     * 如果 openid 存在数据库中则直接登陆
     * 否则注册
     *
     * @param access_token
     * @param openid
     * @param session
     * @return
     */
    public String login(String access_token, String openid, HttpSession session) throws HttpException {

        // 判断是否已经存在于数据库中
        User user = userMapper.selectByOpenid(openid);

        // 不存在，注册用户信息
        if (user == null) {
            // 获取用户信息
            String messageJson = getUserInformation(access_token, openid);

            // 将json信息转化为map格式
            Map<String, String> map = GsonUtil.getGson().fromJson(
                    messageJson, new TypeToken<Map<String, String>>() {
                    }.getType());

            // 如果ret不为0则获取失败，返回错误信息
            if (!"0".equals(map.get("ret"))) {
                return GsonUtil.getErrorJson(map.get("msg"));
            }

            // 保存
            user = new User();
            user.setOpenid(openid);
            user.setUsername(map.get("nickname"));
            user.setHeadUrl(map.get("figureurl_qq_2"));
            String gender = map.get("gender");
            user.setSex(gender.equals("男") ? User.SEX_MALE :
                    (gender.equals("女") ? User.SEX_FEMALE : null));
            userMapper.insertSelective(user);
        }
        // 登陆
        session.setAttribute("user", user);
        return GsonUtil.getSuccessJson(user);
    }

    /**
     * 发送url请求获取用户信息
     *
     * @param access_token
     * @param openid
     * @return
     * @throws HttpException
     */
    private String getUserInformation(String access_token, String openid) throws HttpException {
        String reslut = HttpsUtil.sentGet("https://graph.qq.com/user/get_user_info",
                new String[]{"access_token", access_token,
                        "oauth_consumer_key", appid, "openid", openid});
        return reslut;
    }
}
